<template>
  <el-drawer
    v-model="visible"
    title="浏览历史"
    direction="rtl"
    size="400px"
    destroy-on-close
  >
    <div class="history-drawer-content">
      <div class="drawer-header">
        <el-input
          v-model="searchQuery"
          placeholder="搜索课程名称..."
          clearable
          prefix-icon="Search"
        />
        <el-button type="danger" plain @click="confirmClearAll" :disabled="!hasHistory">清空历史</el-button>
      </div>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="!hasHistory" class="empty-history">
        <el-empty description="暂无浏览历史" :image-size="120">
          <el-button type="primary" @click="goToCourses">去浏览课程</el-button>
        </el-empty>
      </div>
      
      <div v-else class="history-list">
        <el-timeline>
          <el-timeline-item
            v-for="(group, date) in groupedHistory"
            :key="date"
            :timestamp="formatDate(date)"
            placement="top"
            type="primary"
          >
            <div class="history-group">
              <div 
                v-for="history in group" 
                :key="history.id" 
                class="history-item"
              >
                <div class="history-card" @click="viewCourse(history.course)">
                  <div class="course-image">
                    <img :src="formatImageUrl(history.course.coverImage)" :alt="history.course.title">
                  </div>
                  <div class="course-info">
                    <h4 class="course-title">{{ history.course.title }}</h4>
                    <p class="course-institution">{{ history.course.institution }}</p>
                    <p class="browse-time">{{ formatTime(history.createTime) }}</p>
                  </div>
                  <el-button 
                    class="delete-btn" 
                    type="danger" 
                    circle 
                    size="small"
                    :icon="Delete"
                    @click.stop="confirmDelete(history)"
                  />
                </div>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      
      <div class="drawer-footer" v-if="hasHistory && totalPages > 1">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
          background
        />
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Search, Delete } from '@element-plus/icons-vue'
import axios from 'axios'
import dayjs from 'dayjs'
import { useUserStore } from '@/store/user'

const props = defineProps({
  visible: Boolean
})

const emit = defineEmits(['update:visible'])

// 双向绑定的处理
const visible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const router = useRouter()
const userStore = useUserStore()
const API_BASE_URL = process.env.VUE_APP_BASE_API || '/api'

// 数据
const loading = ref(false)
const historyList = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const totalPages = ref(0)

// 计算属性
const hasHistory = computed(() => historyList.value.length > 0)

// 按日期分组历史记录
const groupedHistory = computed(() => {
  const grouped = {}
  
  historyList.value.forEach(item => {
    const date = dayjs(item.createTime).format('YYYY-MM-DD')
    
    if (!grouped[date]) {
      grouped[date] = []
    }
    
    grouped[date].push(item)
  })
  
  return grouped
})

// 监听搜索和页码变化
watch([searchQuery, currentPage], () => {
  if (visible.value) {
    fetchHistory()
  }
}, { immediate: false })

// 监听抽屉打开
watch(visible, (newVal) => {
  if (newVal) {
    currentPage.value = 1
    fetchHistory()
  }
})

// 格式化日期
const formatDate = (dateStr) => {
  const today = dayjs().format('YYYY-MM-DD')
  const yesterday = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
  
  if (dateStr === today) {
    return '今天'
  } else if (dateStr === yesterday) {
    return '昨天'
  }
  
  return dateStr
}

// 格式化时间
const formatTime = (timestamp) => {
  return dayjs(timestamp).format('HH:mm:ss')
}

// 格式化图片URL
const formatImageUrl = (url) => {
  if (!url) return 'https://via.placeholder.com/100x70?text=No+Image'
  
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  
  return `${API_BASE_URL}${url.startsWith('/') ? '' : '/'}${url}`
}

// 方法
const fetchHistory = async () => {
  loading.value = true
  
  try {
    if (!userStore.isLoggedIn || !userStore.userInfo || !userStore.userInfo.id) {
      ElMessage.error('用户未登录或用户信息缺失')
      loading.value = false
      return
    }
    
    const userId = userStore.userInfo.id
    
    const apiUrl = `/browse-history/user/${userId}`
    
    const response = await axios.get(`${API_BASE_URL}${apiUrl}`, {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        search: searchQuery.value || undefined
      }
    })
    
    // 处理响应数据，适配后端返回的格式
    let responseData = response.data
    
    // 检查是否有data字段，符合Result<T>结构
    if (response.data && response.data.data) {
      responseData = response.data.data
    }
    
    // 支持不同结构的分页数据
    const records = responseData.records || responseData.content || []
    const totalElements = responseData.total || responseData.totalElements || 0
    const pages = responseData.pages || responseData.totalPages || 0
    
    historyList.value = records||[]
    total.value = totalElements||0
    totalPages.value = pages||0
  } catch (error) {
    console.error('Failed to fetch browse history:', error)
    ElMessage.error('获取浏览历史失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page) => {
  currentPage.value = page
}

const viewCourse = (course) => {
  visible.value = false
  router.push(`/courses/${course.id}`)
}

const goToCourses = () => {
  visible.value = false
  router.push('/courses')
}

const confirmDelete = (history) => {
  ElMessageBox.confirm('确定要删除这条浏览记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteHistory(history.id)
  }).catch(() => {})
}

const deleteHistory = async (id) => {
  try {
    await axios.delete(`${API_BASE_URL}/browse-history/${id}`)
    ElMessage.success('删除成功')
    fetchHistory()
  } catch (error) {
    console.error('Failed to delete browse history:', error)
    ElMessage.error('删除失败')
  }
}

const confirmClearAll = () => {
  ElMessageBox.confirm('确定要清空所有浏览历史吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    clearAllHistory()
  }).catch(() => {})
}

const clearAllHistory = async () => {
  try {
    if (!userStore.isLoggedIn || !userStore.userInfo || !userStore.userInfo.id) {
      ElMessage.error('用户未登录或用户信息缺失')
      return
    }
    
    const userId = userStore.userInfo.id
    
    await axios.delete(`${API_BASE_URL}/browse-history/user/${userId}/clear`)
    ElMessage.success('清空成功')
    historyList.value = []
    total.value = 0
    totalPages.value = 0
  } catch (error) {
    console.error('Failed to clear browse history:', error)
    ElMessage.error('清空失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  if (visible.value) {
    fetchHistory()
  }
})
</script>

<style lang="scss" scoped>
.history-drawer-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 16px;
}

.drawer-header {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  
  .el-input {
    flex: 1;
  }
}

.loading-container,
.empty-history {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 16px;
  margin-right: -16px;
}

.history-group {
  margin-bottom: 16px;
}

.history-item {
  margin-bottom: 12px;
}

.history-card {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  position: relative;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    
    .delete-btn {
      opacity: 1;
    }
  }
  
  .course-image {
    width: 100px;
    height: 70px;
    overflow: hidden;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.5s;
      
      &:hover {
        transform: scale(1.05);
      }
    }
  }
  
  .course-info {
    flex: 1;
    padding: 8px 12px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .course-title {
      margin: 0;
      font-size: 14px;
      font-weight: 500;
      line-height: 1.3;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }
    
    .course-institution {
      margin: 4px 0 0;
      font-size: 12px;
      color: #666;
    }
    
    .browse-time {
      margin: 0;
      font-size: 12px;
      color: #999;
    }
  }
  
  .delete-btn {
    position: absolute;
    top: 8px;
    right: 8px;
    opacity: 0;
    transition: opacity 0.3s;
  }
}

.drawer-footer {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-timeline-item__tail) {
  border-left: 2px solid #e6ebf5;
}

:deep(.el-timeline-item__node--primary) {
  background-color: var(--el-color-primary);
}

:deep(.el-timeline-item__timestamp) {
  color: #606266;
  font-weight: 600;
  margin-bottom: 8px;
}
</style> 